package com.uinnova.product.eam.service.impl;

import com.binary.core.exception.BinaryException;
import com.binary.core.util.BinaryUtils;
import com.binary.jdbc.Page;
import com.uinnova.product.eam.dao.SysApiKeyDao;
import com.uinnova.product.eam.model.es.SysApiKeyInfo;
import com.uinnova.product.eam.service.SysApiKeyService;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.UUID;

@Service
public class SysApiKeyServiceImpl implements SysApiKeyService {

    @Resource
    private SysApiKeyDao sysApiKeyDao;

    @Override
    public List<SysApiKeyInfo> list() {
        BoolQueryBuilder query = QueryBuilders.boolQuery();
        Page<SysApiKeyInfo> sysApiKeyInfoPage = sysApiKeyDao.getSortListByQuery(1, 3000, query, "createTime", true);
        return sysApiKeyInfoPage.getData();
    }

    @Override
    public SysApiKeyInfo saveOrUpdate(SysApiKeyInfo sysApiKeyInfo) {
        if (sysApiKeyInfo.getStatus() == null) {
            sysApiKeyInfo.setStatus(1);
        }
        SysApiKeyInfo info = sysApiKeyInfo;
        if (!BinaryUtils.isEmpty(sysApiKeyInfo.getId())) {
            info = sysApiKeyDao.getById(sysApiKeyInfo.getId());
            if (BinaryUtils.isEmpty(info)) {
                throw new BinaryException("系统apiKey未查到！");
            }
            info.setSysName(sysApiKeyInfo.getSysName());
        }

        Long id = sysApiKeyDao.saveOrUpdate(info);
        return sysApiKeyDao.getById(id);
    }

    @Override
    public SysApiKeyInfo createApiKey(SysApiKeyInfo sysApiKeyInfo) {
        SysApiKeyInfo info = sysApiKeyDao.getById(sysApiKeyInfo.getId());
        if (BinaryUtils.isEmpty(info)) {
            throw new BinaryException("系统apiKey未查到！");
        }
        UUID uuid = UUID.randomUUID();
        String apiKey = uuid.toString();
        info.setApiKey(apiKey);
        sysApiKeyDao.saveOrUpdate(info);
        return info;
    }
}
